package com.crazymaker.springcloud.demo.security;

import com.crazymaker.springcloud.common.constants.SessionConstants;
import com.crazymaker.springcloud.standard.basicFacilities.CustomAppContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by 尼恩 on 2019/7/18.
 */

@Slf4j
@Service
public class DemoUserAuthService implements UserDetailsService
{

    private Map<String, String> map = new LinkedHashMap<>();
    {
        map.put("zhangsan", "123456" );
        map.put("lisi", "123456" );
    }


    @Resource
    private PasswordEncoder passwordEncoder;

    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException
    {

        String password = map.get(username);
        if(password==null)
        {
            return null;
        }

        if(null==passwordEncoder)
        {
            passwordEncoder=CustomAppContext.getBean(PasswordEncoder.class);
        }

        return User.builder()
                .username(username)
                .password(passwordEncoder.encode(password))
                .authorities(SessionConstants.USER_INFO)
                .roles("USER" )
                .build();

    }


}
